package com.bilibili.juc.threadlocal;

import java.util.Random;

/**
 * @author zuife
 * @description 需求2：
 * @since 2024-05-05 16:10:43
 */
public class ThreadLocalDemo {
    public static void main(String[] args) {
        House house = new House();
        for (int i = 0; i < 5; i++) {
            new Thread(() -> {
                int size = new Random().nextInt(5) + 1;

                try {
                    for (int j = 0; j < size; j++) {
                        house.saleHouse();
                        house.saleVolumeByThreadLocal();
                    }
                    System.out.println("Thread:" + Thread.currentThread().getName() + " 号销售卖出： " + house.saleVolume.get());
                } finally {
                    house.saleVolume.remove(); //必须回收自定义的ThreadLocal变量
                }
            }, String.valueOf(i)).start();
        }
        //暂停1秒
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        System.out.println("共计卖出多少套:" + house.saleCount);
    }
}

class House {
    ThreadLocal<Integer> saleVolume = ThreadLocal.withInitial(() -> 0);
    int saleCount;
    public synchronized void saleHouse() {
        saleCount++;
    }
    public void saleVolumeByThreadLocal() {
        saleVolume.set(saleVolume.get() + 1);
    }
}
